package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordBatchRequest;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordCreateRequest;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordQueryRequest;
import com.blog.cmrpersonalblog.dto.sensitiveword.respnose.SensitiveWordResponse;
import com.blog.cmrpersonalblog.service.SensitiveWordManagementService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 敏感词管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/sensitive-word")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckRole("admin")
public class SensitiveWordManagementController {

   @Resource
    private SensitiveWordManagementService sensitiveWordManagementService;

    /**
     * 分页查询敏感词列表
     */
    @GetMapping("/page")
    public Result<IPage<SensitiveWordResponse>> getSensitiveWordPage(@Validated SensitiveWordQueryRequest query) {
        log.info("管理员分页查询敏感词列表");
        try {
            IPage<SensitiveWordResponse> result = sensitiveWordManagementService.getSensitiveWordPage(query);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("分页查询敏感词列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取敏感词详情
     */
    @GetMapping("/{id}")
    public Result<SensitiveWordResponse> getSensitiveWordById(@PathVariable Long id) {
        log.info("管理员获取敏感词详情，ID：{}", id);
        try {
            SensitiveWordResponse result = sensitiveWordManagementService.getSensitiveWordById(id);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取敏感词详情失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 创建敏感词
     */
    @PostMapping
    public Result<Long> createSensitiveWord(@RequestBody @Validated SensitiveWordCreateRequest request) {
        log.info("管理员创建敏感词：{}", request.getWord());
        try {
            Long id = sensitiveWordManagementService.createSensitiveWord(request);
            return Result.success("创建成功", id);
        } catch (Exception e) {
            log.error("创建敏感词失败", e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新敏感词
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateSensitiveWord(@PathVariable Long id,
                                             @RequestBody @Validated SensitiveWordCreateRequest request) {
        log.info("管理员更新敏感词，ID：{}，内容：{}", id, request.getWord());
        try {
            Boolean result = sensitiveWordManagementService.updateSensitiveWord(id, request);
            return Result.success("更新成功", result);
        } catch (Exception e) {
            log.error("更新敏感词失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除敏感词
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteSensitiveWord(@PathVariable Long id) {
        log.info("管理员删除敏感词，ID：{}", id);
        try {
            Boolean result = sensitiveWordManagementService.deleteSensitiveWord(id);
            return Result.success("删除成功", result);
        } catch (Exception e) {
            log.error("删除敏感词失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量创建敏感词
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> batchCreateSensitiveWords(@RequestBody @Validated SensitiveWordBatchRequest request) {
        log.info("管理员批量创建敏感词，数量：{}", request.getWords().size());
        try {
            Map<String, Object> result = sensitiveWordManagementService.batchCreateSensitiveWords(request);
            return Result.success("批量创建完成", result);
        } catch (Exception e) {
            log.error("批量创建敏感词失败", e);
            return Result.error("批量创建失败：" + e.getMessage());
        }
    }

    /**
     * 启用敏感词
     */
    @PostMapping("/{id}/enable")
    public Result<Boolean> enableSensitiveWord(@PathVariable Long id) {
        log.info("管理员启用敏感词，ID：{}", id);
        try {
            Boolean result = sensitiveWordManagementService.batchUpdateStatus(List.of(id), 1);
            return Result.success("启用成功", result);
        } catch (Exception e) {
            log.error("启用敏感词失败", e);
            return Result.error("启用失败：" + e.getMessage());
        }
    }

    /**
     * 禁用敏感词
     */
    @PostMapping("/{id}/disable")
    public Result<Boolean> disableSensitiveWord(@PathVariable Long id) {
        log.info("管理员禁用敏感词，ID：{}", id);
        try {
            Boolean result = sensitiveWordManagementService.batchUpdateStatus(List.of(id), 0);
            return Result.success("禁用成功", result);
        } catch (Exception e) {
            log.error("禁用敏感词失败", e);
            return Result.error("禁用失败：" + e.getMessage());
        }
    }

    /**
     * 更新敏感词状态
     */
    @PutMapping("/{id}/status")
    public Result<Boolean> updateSensitiveWordStatus(@PathVariable Long id, @RequestParam Integer status) {
        log.info("管理员更新敏感词状态，ID：{}，状态：{}", id, status);
        try {
            Boolean result = sensitiveWordManagementService.batchUpdateStatus(List.of(id), status);
            return Result.success("状态更新成功", result);
        } catch (Exception e) {
            log.error("更新敏感词状态失败", e);
            return Result.error("状态更新失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新敏感词状态
     */
    @PutMapping("/batch/status")
    public Result<Boolean> batchUpdateStatus(@RequestParam List<Long> ids, @RequestParam Integer status) {
        log.info("管理员批量更新敏感词状态，数量：{}，状态：{}", ids.size(), status);
        try {
            Boolean result = sensitiveWordManagementService.batchUpdateStatus(ids, status);
            return Result.success("批量更新状态成功", result);
        } catch (Exception e) {
            log.error("批量更新敏感词状态失败", e);
            return Result.error("批量更新状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除敏感词
     */
    @DeleteMapping("/batch")
    public Result<Boolean> batchDeleteSensitiveWords(@RequestParam List<Long> ids) {
        log.info("管理员批量删除敏感词，数量：{}", ids.size());
        try {
            Boolean result = sensitiveWordManagementService.batchDeleteSensitiveWords(ids);
            return Result.success("批量删除成功", result);
        } catch (Exception e) {
            log.error("批量删除敏感词失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 导入敏感词库
     */
    @PostMapping("/import")
    public Result<Map<String, Object>> importSensitiveWords(
            @RequestParam("file") MultipartFile file,
            @RequestParam String type,
            @RequestParam Integer severity,
            @RequestParam String filterMode,
            @RequestParam(defaultValue = "false") Boolean overwrite) {
        log.info("管理员导入敏感词库，文件名：{}", file.getOriginalFilename());
        try {
            Map<String, Object> result = sensitiveWordManagementService.importSensitiveWords(file, type, severity, filterMode, overwrite);
            return Result.success("导入完成", result);
        } catch (Exception e) {
            log.error("导入敏感词库失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导出敏感词库
     */
    @GetMapping("/export")
    public void exportSensitiveWords(@Validated SensitiveWordQueryRequest query, HttpServletResponse response) {
        log.info("管理员导出敏感词库");
        try {
            sensitiveWordManagementService.exportSensitiveWords(query, response);
        } catch (Exception e) {
            log.error("导出敏感词库失败", e);
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getSensitiveWordStatistics() {
        log.info("管理员获取敏感词统计信息");
        try {
            Map<String, Object> result = sensitiveWordManagementService.getSensitiveWordStatistics();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取敏感词统计信息失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词类型分布
     */
    @GetMapping("/statistics/type-distribution")
    public Result<Map<String, Long>> getTypeDistribution() {
        log.info("管理员获取敏感词类型分布");
        try {
            Map<String, Long> result = sensitiveWordManagementService.getTypeDistribution();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取敏感词类型分布失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词严重程度分布
     */
    @GetMapping("/statistics/severity-distribution")
    public Result<Map<String, Long>> getSeverityDistribution() {
        log.info("管理员获取敏感词严重程度分布");
        try {
            Map<String, Long> result = sensitiveWordManagementService.getSeverityDistribution();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取敏感词严重程度分布失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词过滤模式分布
     */
    @GetMapping("/statistics/filter-mode-distribution")
    public Result<Map<String, Long>> getFilterModeDistribution() {
        log.info("管理员获取敏感词过滤模式分布");
        try {
            Map<String, Long> result = sensitiveWordManagementService.getFilterModeDistribution();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取敏感词过滤模式分布失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门敏感词
     */
    @GetMapping("/popular")
    public Result<List<SensitiveWordResponse>> getPopularWords(@RequestParam(defaultValue = "10") Integer limit) {
        log.info("管理员获取热门敏感词，限制数量：{}", limit);
        try {
            List<SensitiveWordResponse> result = sensitiveWordManagementService.getPopularWords(limit);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取热门敏感词失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 刷新敏感词缓存
     */
    @PostMapping("/refresh-cache")
    public Result<Boolean> refreshSensitiveWordCache() {
        log.info("管理员刷新敏感词缓存");
        try {
            Boolean result = sensitiveWordManagementService.refreshSensitiveWordCache();
            return Result.success("刷新缓存成功", result);
        } catch (Exception e) {
            log.error("刷新敏感词缓存失败", e);
            return Result.error("刷新缓存失败：" + e.getMessage());
        }
    }

    /**
     * 清理过期的匹配统计
     */
    @PostMapping("/clean-expired-stats")
    public Result<Integer> cleanExpiredStats(@RequestParam(defaultValue = "30") Integer days) {
        log.info("管理员清理过期的匹配统计，保留天数：{}", days);
        try {
            Integer result = sensitiveWordManagementService.cleanExpiredStats(days);
            return Result.success("清理完成", result);
        } catch (Exception e) {
            log.error("清理过期的匹配统计失败", e);
            return Result.error("清理失败：" + e.getMessage());
        }
    }

    /**
     * 测试敏感词过滤
     */
    @PostMapping("/test-filter")
    public Result<Map<String, Object>> testSensitiveWordFilter(@RequestParam String content) {
        log.info("管理员测试敏感词过滤，内容长度：{}", content != null ? content.length() : 0);
        try {
            Map<String, Object> result = sensitiveWordManagementService.testSensitiveWordFilter(content);
            return Result.success("测试完成", result);
        } catch (Exception e) {
            log.error("测试敏感词过滤失败", e);
            return Result.error("测试失败：" + e.getMessage());
        }
    }
}